<template>
  <div class>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 选择分类框 -->
      <el-row class="cat_opt">
          <el-col>
            <span>选择商品分类: </span>
            <!-- hover级联选择框 -->
            <el-cascader
              v-model="paramslist"
              :options="catelist"
              :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children'}"
              @change="paramsChange"
              :show-all-levels="false"
              >
            </el-cascader>
          </el-col>
      </el-row>
      <!-- tabs -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数内容 -->
          <el-button @click="addDialogVisible = true" type="primary" size="mini" :disabled="isBtnDisabled">添加参数</el-button>  
          <!-- 动态参数表格 -->
          <el-table
          :data="manyTableData"
          border
          stripe
          >
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template v-slot="scope">
              <!-- 循环渲染tag -->
              <el-tag @close="handleClose(idx, scope.row)" closable  v-for="(item, idx) of scope.row.attr_vals" :key="idx">{{item}}</el-tag>
              <!-- 可添加的tag -->
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <!-- 作用域插槽 -->
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button @click="showEditDialog(scope.row.attr_id)" type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
              <el-button @click="removeParams(scope.row.attr_id)" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 静态属性内容 -->
          <el-button @click="addDialogVisible = true" type="primary" size="mini" :disabled="isBtnDisabled">添加属性</el-button>  
          <!-- 静态属性表格 -->
          <el-table
          :data="onlyTableData"
          border
          stripe
          >
          <!-- 展开列 -->
           <el-table-column type="expand">
            <template v-slot="scope">
              <!-- 循环渲染tag -->
              <el-tag @close="handleClose(idx, scope.row)" closable  v-for="(item, idx) of scope.row.attr_vals" :key="idx">{{item}}</el-tag>
              <!-- 可添加的tag -->
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <!-- 作用域插槽 -->
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button @click="showEditDialog(scope.row.attr_id)" type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
              <el-button @click="removeParams(scope.row.attr_id)" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数和静态属性的公用对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDilogClosed"
      >
      <!--  -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDilogClosed"
      >
      <!--  -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
    data() {
      return {
        // 商品分类列表
        catelist: [],
        // 定义的id数组
        paramslist: [],
        // Tabs选中的类名
        activeName: 'many',
        // 动态参数数据
        manyTableData: [],
        // 静态参数数据
        onlyTableData: [],
        // 添加表格对话框
        addDialogVisible: false,
        // 添加表格的表单对象
        addForm: {
          attr_name: ''
        },
        // 添加的验证规则
        addFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
          ]
        },
        // 编辑对话框状态
        editDialogVisible: false,
        // 编辑对象
        editForm: {
          attr_name: ''
        },
        // 编辑的验证规则
        editFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
          ]
        }
      }
    },
    created() {
        this.getCateList()
    },
    methods: {
      // 获取所有的商品分类
      async getCateList() {
        const {data: res} = await this.$axios.get('categories')
        if(res.meta.status !== 200) {
          return this.$message.error('获取商品列表失败')  
        }
        this.catelist = res.data
      },
      // 级联选择框参数变化
      paramsChange (){
        // 级联选择框改变时获取参数
        this.getParamsData()
      },
      // tabs切换事件
      handleTabClick() {
        // 标签切换时获取参数
        this.getParamsData()
      },
      // 获取参数的列表数据
      async getParamsData (){
          // 没有选中第三级
        if (this.paramslist.length !== 3) {
          this.paramslist = []
          // 没有选择时数据清空
          this.manyTableData = []
          this.onlyTableData = []
          return 
        }
        // 选中三级的处理
        const {data: res} = await this.$axios.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})
         if(res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败')  
        }
        // 修改获取到数据
        res.data.forEach(item => {
          // 修改数据---处理当没有数据时返回一个空的数组                        
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框的像是与隐藏
          item.inputVisible = false
          // 文本框输入的值
          item.inputValue = ''

        })
        console.log(res)
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        }else {
          this.onlyTableData = res.data
        }
      },
      // 监听对话框的关闭事件
      addDilogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // 点击确定请求添加的数据
      addParams() {
        this.$refs.addFormRef.validate(async valid => {
          if(!valid) return
          const {data: res} = await this.$axios.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })
          if(res.meta.status !== 201) {
            return this.$message.error('添加失败')
          }
          this.$message.success('添加成功')
          this.addDialogVisible = false
          this.getParamsData()

        })
      },
      // 点击编辑显示对话框
      async showEditDialog(id) {
        const {data: res} = await this.$axios.get(`categories/${this.cateId}/attributes/${id}`, {
          params: {
            attr_sel: this.activeName
          }
        })
         
        this.editForm = res.data 
        this.editDialogVisible = true
      },
      editDilogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      // 点击按钮修改参数信息
      editParams() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          const {data: res} = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 200){
            return this.$message.error('修改失败')
          }
          this.$message.success('修改成功')
          this.getParamsData()
          this.editDialogVisible = false
        })
      },
      // 根据id删除参数
      async removeParams(id) {
        const confirmRes = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmRes !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        // 删除
        const {data: res} = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`)
        if(res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getParamsData()
      },
      // 文本框失去焦点或按下enter建触发
      async handleInputConfirm(row) {
        // 去除首位空格-----还等于0就是不合法
        if(row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        // 输入和合法值的处理-----将输入的值添加到循环的数组中, 并去除前后的空格
        row.attr_vals.push(row.inputValue.trim())
        // 重置为默认
        row.inputValue = ''
        row.inputVisible = false

        this.saveAttrVals(row)
      },
      // 点击按钮切换到输入框
      showInput(row){
        row.inputVisible = true
        // 官网自动获取焦点
        // $nextTick 方法的作用就是, 当页面上的元素被重新渲染之后, 才会指定回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        })
      },
      // 展开列中attr_vals删除修改的方法保存到数据库
      async saveAttrVals(row){
        // 发起请求保存到数据库中
        const {data: res} = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name:row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        if (res.meta.status !== 200){
            return this.$message.error('修改失败')
        }

        this.$message.success('修改成功')
      },
      // 删除对应点参数
      handleClose(idx, row) {
        row.attr_vals.splice(idx, 1)
        this.saveAttrVals(row)
      }
    },
    computed: {
      // 如果id数组长度是三说用选择了参数返回false,否则true
      isBtnDisabled(){
          if (this.paramslist.length !== 3) {
            return true  
          }
          return false
      },
      // 当前选中的三级分类id
      cateId() {
        if (this.paramslist.length === 3) {
          return this.paramslist[2]
        }
        return null
      },
      // 动态计算标题的文本
      titleText(){
        if(this.activeName === 'many') {
          return '动态参数'
        }else {
          return '静态属性'
        }
      }
    }
}
</script>
<style lang='less' scoped>
.cat_opt{
    margin: 15px 0
}
.el-tag{
  margin: 10px 
}
.input-new-tag {
  width: 120px;
}
</style>
